﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models;
using System.Threading.Tasks;
using System.Linq;
using System.Security.Claims;
using IRepository;
using System;
using Helper;
using Microsoft.AspNetCore.Cors;
using Models.Entity;
using System.Data;
using System.Collections.Generic;
using course.Config;
using Microsoft.Extensions.Options;

namespace course.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiController]
    [EnableCors]
    [Authorize]
    public class WeekCourseController : ControllerBase
    {
        IWeekCourseRepository _repository;
        AppConfig _appConfig;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="appConfig"></param>
        public WeekCourseController(IWeekCourseRepository repository, IOptions<AppConfig> appConfig)
        {
            this._repository = repository;
            this._appConfig = appConfig.Value;
        }

        /// <summary>
        /// 添加课时
        /// </summary>
        /// <param name="inEnt"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultObj<int>> AddWeekCourse(DtoSave<DtoAddWeekCourse> inEnt)
        {
            ResultObj<int> reObj = new ResultObj<int>();
            try
            {
                reObj = await _repository.AddWeekCourse(inEnt.data);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(typeof(WeekCourseController), ex.ToString());
                reObj.msg = ex.Message;
                reObj.success = false;
            }
            return reObj;
        }

        /// <summary>
        /// 删除课时
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultObj<int>> DeleteWeekCourse(DtoDo<int> inObj)
        {
            ResultObj<int> reObj = new ResultObj<int>();
            try
            {
                reObj = await _repository.DeleteWeekCourse(inObj);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(typeof(WeekCourseController), ex.ToString());
                reObj.msg = ex.Message;
                reObj.success = false;
            }
            return reObj;
        }


        /// <summary>
        /// 删除单条
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultObj<int>> delete(DtoWeekCourse inObj)
        {
            ResultObj<int> reObj = new ResultObj<int>();
            try
            {
                reObj = await _repository.Delete(inObj);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(typeof(WeekCourseController), ex.ToString());
                reObj.msg = ex.Message;
                reObj.success = false;
            }
            return reObj;
        }

        /// <summary>
        /// 生成课表，返回生成课目数
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultObj<int>> MakeWeekCourse(DtoDo<int> inObj)
        {
            ResultObj<int> reObj = new ResultObj<int>();

            reObj = await _repository.MakeWeekCourse(inObj);

            return reObj;
        }

        /// <summary>
        /// 获取年级课表
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultObj<CClassesWeekCourseEntityView>> GetWeekCourse(DtoWeekCourse inObj)
        {
            ResultObj<CClassesWeekCourseEntityView> reObj = new ResultObj<CClassesWeekCourseEntityView>();
            try
            {
                reObj = await _repository.GetWeekCourse(inObj);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(typeof(WeekCourseController), ex.ToString());
                reObj.msg = ex.Message;
                reObj.success = false;
            }
            return reObj;
        }
        /// <summary>
        /// 获取所有班级课表
        /// </summary>
        [HttpPost]
        public Task<ResultObj<Dictionary<string, string>>> CourseTable()
        {
            return _repository.CourseTable();
        }

        /// <summary>
        /// 获取班级课表
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ResultObj<CClassesEntity>> GetClassesCourse(DtoDo<int> inObj)
        {
            return _repository.GetClassesCourse(inObj);
        }

        /// <summary>
        /// 获取班级课表
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ResultObj<CTeacherEntity>> GetTeacherCourse(DtoDo<int> inObj)
        {
            return _repository.GetTeacherCourse(inObj);
        }

        /// <summary>
        /// 导出课表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> downCourse()
        {
            var reObj = await _repository.CourseTable();
            string reStr = "";
            List<string> titleRow = new List<string>() { "班级" };
            for (int day = 1; day <= this._appConfig.Course.DayNum + 1; day++)
            {
                for (int num = 1; num <= this._appConfig.Course.ClassesNum + 1; num++)
                {
                    titleRow.Add($"周{day}第{num}节");
                }
            }
            reStr += string.Join(",", titleRow) + "\r\n";
            string[] row = new string[titleRow.Count];
            for (int i = 0; i < row.Length; i++)
            {
                row[i] = "-";
            }
            foreach (var classes in reObj.dataList)
            {
                foreach (var key in classes.Keys)
                {
                    if (key.Equals("班级"))
                    {
                        if ("高一实验班1" == classes[key])
                        {
                            Console.WriteLine(classes[key]);
                        }
                        row[0] = classes[key];
                    }
                    else
                    {
                        var day = Convert.ToInt32(key.Split('-')[0]);
                        var num = Convert.ToInt32(key.Split('-')[1]);
                        row[(day - 1) * (this._appConfig.Course.ClassesNum + 1) + num] = classes[key].Replace(",", "-");
                    }
                }
                reStr += string.Join(",", row) + "\r\n";
                for (int i = 0; i < row.Length; i++)
                {
                    row[i] = "-";
                }
            }
            return File(System.Text.Encoding.Default.GetBytes(reStr), "application/octet-stream", $"课表.csv");
        }


        /// <summary>
        /// 导出班级课表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> downClassesCourse()
        {
            ResultObj<Dictionary<string, string>> reObj = await _repository.CourseTable();
            Dictionary<string, Dictionary<string, string>> excelXls = new Dictionary<string, Dictionary<string, string>>();
            foreach (var classes in reObj.dataList)
            {
                string name = "";
                Dictionary<string, string> valueList = new Dictionary<string, string>();
                valueList.Add("1|2", "周一");
                valueList.Add("1|3", "周二");
                valueList.Add("1|4", "周三");
                valueList.Add("1|5", "周四");
                valueList.Add("1|6", "周五");
                valueList.Add("1|7", "周六");

                valueList.Add("2|1", "第一节");
                valueList.Add("3|1", "第二节");
                valueList.Add("4|1", "第三节");
                valueList.Add("5|1", "第四节");
                valueList.Add("6|1", "第五节");
                valueList.Add("7|1", "第六节");
                valueList.Add("8|1", "第七节");
                valueList.Add("9|1", "第八节");
                foreach (var key in classes.Keys)
                {
                    if (key.Equals("班级"))
                    {
                        name = classes[key];
                    }
                    else
                    {
                        var day = Convert.ToInt32(key.Split('-')[0]);
                        var num = Convert.ToInt32(key.Split('-')[1]);
                        valueList.Add($"{num + 1}|{day + 1}", classes[key].Replace(",", "-"));
                    }
                }
                excelXls.Add(name, valueList);
            }
            return File(ExcelHelper.MakeExcel(excelXls), "application/octet-stream", $"班级课表.xlsx");
        }


        /// <summary>
        /// 导出老师课表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> downTeacherCourse()
        {
            ResultObj<Dictionary<string, string>> reObj = await _repository.TeacherCourseTable();
            Dictionary<string, Dictionary<string, string>> excelXls = new Dictionary<string, Dictionary<string, string>>();
            foreach (var classes in reObj.dataList)
            {
                string name = "";
                Dictionary<string, string> valueList = new Dictionary<string, string>();
                valueList.Add("1|2", "周一");
                valueList.Add("1|3", "周二");
                valueList.Add("1|4", "周三");
                valueList.Add("1|5", "周四");
                valueList.Add("1|6", "周五");
                valueList.Add("1|7", "周六");

                valueList.Add("2|1", "第一节");
                valueList.Add("3|1", "第二节");
                valueList.Add("4|1", "第三节");
                valueList.Add("5|1", "第四节");
                valueList.Add("6|1", "第五节");
                valueList.Add("7|1", "第六节");
                valueList.Add("8|1", "第七节");
                valueList.Add("9|1", "第八节");
                foreach (var key in classes.Keys)
                {
                    if (key.Equals("老师"))
                    {
                        name = classes[key];
                    }
                    else
                    {
                        var day = Convert.ToInt32(key.Split('-')[0]);
                        var num = Convert.ToInt32(key.Split('-')[1]);
                        valueList.Add($"{num + 1}|{day + 1}", classes[key].Replace(",", "-"));
                    }
                }
                while (excelXls.ContainsKey(name))
                {
                    name += "(1)";
                }
                excelXls.Add(name, valueList);
            }
            return File(ExcelHelper.MakeExcel(excelXls), "application/octet-stream", $"老师课表.xlsx");
        }

    }
}